import logging
from loguru import logger
from op_drf.dj_utils import flow_code_manage
from op_drf.dj_utils import create_by_serializer
from op_drf.serializers import CustomModelSerializer, BaseSerializer
from op_drf.validator import CustomUniqueValidator
from rest_framework import serializers
from apps.prescription.models import (
Prescription,
Drug
)

import datetime

# 新建处方信息
class WritePrescriptionSerializer(CustomModelSerializer):
    OrderDt = serializers.DateField(required=True,format="%Y-%m-%d")
    OrderDtm = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S",required=True)
    # OrderNum = serializers.CharField(required=False,
    #                                  validators=[CustomUniqueValidator(queryset=Prescription.objects.all(), message="当前订单号已经存在,请勿重复添加！")],)
    # 默认专业方
    OrderType = serializers.CharField(default="0")
    # 科室
    WardCd = serializers.CharField(required=True)

    def create(self, validated_data):
        # 增加数据的验证
        logger.debug("请求携带的数据： %s" % validated_data)
        logger.debug("请求携带的数据： %s" % validated_data)
        OrderNum = validated_data.get("OrderNum",None)
        logger.debug(OrderNum)
        if OrderNum:
            logger.debug("有值")
        else:
            serial_num = flow_code_manage(value="prescription_order")
            if self.Meta.model.objects.filter(orderNum=serial_num):
                raise Exception("数据库中已存在该流水号！")
            validated_data["OrderNum"] = serial_num

        return super().create(validated_data)

    class Meta:
        model = Prescription
        fields = "__all__"


class WriteDrugSerializer(CustomModelSerializer):
    # 药品名称
    MedNm = serializers.CharField(required=True)
    # 药品备注
    MedNote = serializers.CharField(required=False)

    def create(self, validated_data):

        # 增加数据的验证s
        logger.debug("请求携带的数据： %s" % validated_data)
        return super().create(validated_data)

    def update(self, instance, validated_data):
        logger.debug("请求携带的数据： %s" % validated_data)

        return super().update(instance, validated_data)



    class Meta:
        model = Drug
        fields = "__all__"


'''
读取药品序列化
'''
class ReadDrugSerializer(BaseSerializer):


    class Meta:
        model = Drug
        fields = "__all__"
        # fields = ["id","MedNm","MedNote"]


'''
读取处方列表
'''
class ReadPrescriptionSerializer(BaseSerializer):
    OrderDt = serializers.DateField(required=True, format="%Y-%m-%d")
    OrderDtm = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    MedItems = serializers.SerializerMethodField(method_name="get_drug_data")

    def get_drug_data(self, obj):
        if obj.id:
            drug_list = Drug.objects.filter(is_delete=False,prescrption=obj.id)
            meditems = []
            for drug in drug_list:
                drug_arr = {}
                drug_arr["MedNm"] = drug.MedNm
                drug_arr["MedNote"] = drug.MedNote
                drug_arr["MedSpec"] = drug.MedSpec
                drug_arr["MedUnit"] = drug.MedUnit
                drug_arr["takedt"] = drug.takedt
                MedItemDose = {}
                doselist_time_list = drug.doselist_time.split(",")
                for _index in range(0,len(doselist_time_list)):
                    doselist_time_list[_index] = doselist_time_list[_index]+":"+str(drug.doselist_dose)

                MedItemDose["doselist"] = ";".join(doselist_time_list)
                MedItemDose["takedays"] = drug.takedays
                MedItemDose["drtscd"] = drug.drtscd
                drug_arr["MedItemDose"]=MedItemDose
                meditems.append(drug_arr)

            return meditems

            return ReadDrugSerializer(data=drug_list,many=True).data

    class Meta:
        model = Prescription
        fields = "__all__"
        # fields = ["id","PtntNm","PtntNum","OrderDt","OrderDtm","OrderNum","OrderType","MedItems","is_active","OrderStatus"]
        # fields = ["id","OrderDt","OrderDtm","OrderNum"]

